package com.my.zl.console.common.config;

import java.util.Map;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.context.properties.source.ConfigurationPropertySource;
import org.springframework.boot.context.properties.source.ConfigurationPropertySources;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;

import com.my.zl.console.dao.generator.GeneratorDao;

/**
 * 数据库配置
 */
@Configuration
//@AutoConfigureAfter()
public class DDDaoConfig implements EnvironmentAware{
    
    private static Logger LOGGER = LoggerFactory.getLogger(DDDaoConfig.class);
    
    private String databaseType;
    
    @Autowired
    private Map<String,GeneratorDao> generatorDao;
    
    @Bean
    @Primary
    public GeneratorDao localSqlDao(){
        if(databaseType.contains("oracle")){
            return generatorDao.get("oracleDao");
        }
        else if(databaseType.contains("mysql")){
            return generatorDao.get("mySqlDao");
        }
        else if(databaseType.contains("sqlserver")){
            return generatorDao.get("sqlServerDao");
        }
        else if(databaseType.contains("postgresql")){
            return generatorDao.get("postgreSqlDao");
        }
        else if(databaseType.contains("dm")) {
            return generatorDao.get("damengDao");
        }
        else{
            LOGGER.warn("当前数据库还未实现表结构和表字段读取SQL");
        }
        return generatorDao.get("oracleDao");
    }
    
    @Override
    public void setEnvironment(Environment environment) {
        Iterable<ConfigurationPropertySource> sources = ConfigurationPropertySources.get(environment);
        Binder binder = new Binder(sources);
        BindResult<Properties> bindResult = binder.bind("myself", Properties.class);
        Properties properties = bindResult.get();
        databaseType = properties.getProperty("databaseType");
    }
}
